package com.free.wx;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.text.SimpleDateFormat;

//@Configuration
public class JacksonGlobalConfig {

    @Bean(name = "jackson2ObjectMapperBuilder" )
    /* 观察SpringBoot-2.5.4
     * jackson的自动配置类：JacksonAutoConfiguration 源码
     *  */
    @SuppressWarnings(value = "   deprecation " )
    public Jackson2ObjectMapperBuilder xiaoxuJackson2ObjectMapperBuilder() {
        System.out.println("1.jackson builder注入:" );
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        builder.featuresToEnable(SerializationFeature.WRAP_ROOT_VALUE);

        /* 针对new Date  SimpleDateFormat线程不安全， 建议使用自定义的日期工具类，
         * 此处只做简单演示配置*/
        /* 注意: 使用 yyyy-MM-dd HH:mm:ss.fff 将报错 */
        /* 使用 dateFormat， new Date 和 LocalDateTime 均会产生对应效果*/
        /* new Date 不设置的情况下，默认返回时间戳 */
        builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS" ));
        /* 全局注册自定义序列化器 */
//        builder.serializerByType(JackSonDemo.class, new JackSonDemoSerializer());
        return builder;
    }

    @Bean(name = "jacksonObjectMapper" )
    @Primary
    @ConditionalOnBean(name = {"jackson2ObjectMapperBuilder"})
    /* Jackson的ObjectMapper 是线程安全的， 不过SpringBoot2.5.4源码上使用的是非单例模式，这里和源码保持一致 */
    @Scope("prototype" )
//    @Scope("singleton")
    public ObjectMapper xiaoxuJacksonObjectMapper(@Qualifier("jackson2ObjectMapperBuilder" ) Jackson2ObjectMapperBuilder builder) {
        System.out.println("2.jackson objectMapper注入:" );
        return builder.createXmlMapper(false).build();
    }

}
